from app import constants
from app.models import User, News, Category
from app.utils.common import user_login_check
from app.utils.response_code import RET
from . import index_blu
from flask import render_template, current_app, session, jsonify, request, g


@index_blu.route('/newslist')
def index_news_list():
    # URL： / news_list
    # 请求方式：GET
    # 传入参数：JSON格式
    # 参数
    cid = request.args.get("cid", '1')
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    try:
        filters = [News.status == 0]
        if cid != '1':
            filters.append(News.category_id == cid)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="分页数据获取失败")
    news = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    news_list = [i.to_dict() for i in news]
    return jsonify(errno=RET.OK, errmsg="OK",
                   data={
                       'news_list': news_list,
                       "current_page": current_page,
                       "total_page": total_page,
                       "cid": cid
                   })


@index_blu.route('/', methods=['GET', 'POST'])
@user_login_check
def index():
    # 新闻排行数据
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="新闻获取异常")

    click_news_list = [i.to_dict() for i in news]

    click_rank_class = ['first', 'second', 'third']
    for i in range(7):
        click_rank_class.append('')

    categories = Category.query.all()
    categories_list = [i.to_dict() for i in categories]

    return render_template('news/index.html', data={"user_info": g.user.to_dict() if g.user else '',
                                                    "click_news_list": click_news_list,
                                                    'click_rank_class': click_rank_class,
                                                    "categories_list": categories_list
                                                    })


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")
